package com.example.java_gobang.api;

import com.example.java_gobang.mapper.UserMapper;
import com.example.java_gobang.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class UserAPI {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpSession session) {
        User user = userMapper.selectByName(username);
        log.info("username, {}",username);
        if (user == null || !user.getPassword().equals(password)) {
            log.info("登录失败");
            return new User();
        }
        session.setAttribute("user",user);
        return user;
    }

//    @PostMapping("/login")
//    public Object login(String username, String password, HttpServletRequest request) {
//        User user = userMapper.selectByName(username);
//        log.info("username, {}",username);
//        if (user == null || !user.getPassword().equals(password)) {
//            log.info("登录失败");
//            return new User();
//        }
//        HttpSession session = request.getSession(true);
//        session.setAttribute("user",user);
//        return user;
//    }



    @PostMapping("/register")
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUserName(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            log.info("注册失败");
            return new User();
        }

    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            User newUser = userMapper.selectByName(user.getUserName());
            return newUser;
        } catch (NullPointerException e) {
            return new User();
        }
    }



}

